package project.ia04.agents.gui;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import project.ia04.utils.Data;

public class UpdateProgressBehaviour extends CyclicBehaviour {

	@Override
	public void action() {
		MessageTemplate template = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
													MessageTemplate.MatchConversationId(Data.UPDATEPROGRESS));
		ACLMessage message = myAgent.receive(template);
		if(message != null){
			System.out.println("XAgent --> UpdateProgressBehaviour");
			((XAgent)myAgent).updateProgress(deserialize(message.getContent()));
		}
		else{
			template = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
					MessageTemplate.MatchConversationId(Data.PROGRESS));
			message = myAgent.receive(template);
			if(message != null){
				((XAgent)myAgent).updateMainProgress(message.getContent());
			}
			else
				block();
		}
	}

	private HashMap<String, Integer> deserialize(String content) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map;
		HashMap<String,Integer> res = new HashMap<String, Integer>();
		try {
			map = mapper.readValue(content,Map.class);
			res.put(Data.GAMEPLAYITEM,(Integer)map.get(Data.GAMEPLAYITEM));
			res.put(Data.GRAPHISMITEM,(Integer)map.get(Data.GRAPHISMITEM));
			res.put(Data.SOUNDITEM,(Integer)map.get(Data.SOUNDITEM));
			res.put(Data.CREATIVITYITEM,(Integer)map.get(Data.CREATIVITYITEM));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}
}
